using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Json;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using Code5Systems.FormMaster.Business;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Users;
using DotNetNuke.Security;
using DotNetNuke.Security.Membership;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.Modules;
using Microsoft.VisualBasic;

namespace Code5Systems.FormMaster
{

	#region  Class Utility

	public class Utility
	{
		public Utility()
		{ }
		
		//Gets the Cell Locaiton in the Form Table given a CSV string representing "row,col"
		//and returns a ControlLocation Object
		static public ControlLoaction GetControlLocation(string location)
		{
			return new ControlLoaction(location);
		}
		
		//Cleans up the user input no HTML no Script.
		static public string CleanInput(string input, bool allowMarkup = false)
		{
			string srtCleanInput = "";
			PortalSecurity oPortalSecurity = new PortalSecurity();
			PortalSecurity.FilterFlag flag = PortalSecurity.FilterFlag.NoScripting;
			
			if (!allowMarkup)
			{
				flag = flag | PortalSecurity.FilterFlag.NoMarkup;
			}
			
			srtCleanInput = oPortalSecurity.InputFilter(input, flag);
			
			return srtCleanInput;
			
		}
		
		static public string CleanInputAll(string input)
		{
			string srtCleanInput = "";
			PortalSecurity oPortalSecurity = new PortalSecurity();
			
			srtCleanInput = oPortalSecurity.InputFilter(input, (DotNetNuke.Security.PortalSecurity.FilterFlag) (PortalSecurity.FilterFlag.NoMarkup | PortalSecurity.FilterFlag.NoScripting | PortalSecurity.FilterFlag.MultiLine | PortalSecurity.FilterFlag.NoAngleBrackets | PortalSecurity.FilterFlag.NoSQL));
			
			return srtCleanInput;
			
		}
		
		//When emails are sent in plain text just returns the href attribute
		static public string GetTextModeUrl(string strInput)
		{
			string strUrl = default(string);
			Regex oRexEx = default(Regex);
			Match oMatch = default(Match);
			
			//Return the input is no match is found
			strUrl = strInput;
			
			oRexEx = new Regex("http://.+\\\"");
			
			oMatch = oRexEx.Match(strInput);
			if (oMatch.Success)
			{
				strUrl = oMatch.Value;
				strUrl = strUrl.Replace("\"", "");
			}
			
			return strUrl;
		}
		
		//Validates the format of a given email address
		static public bool ValidateEmailAddressFormat(string email)
		{
			bool bValid = true;
			Regex oRexEx = default(Regex);
			
			oRexEx = new Regex("\\b[a-zA-Z0-9._%!$&*-=^`|~#%\'+/?{}+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}\\b(;\\b[a-zA-Z0-9._%!$&*-=^`|~#%\'+/?{}+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}\\b)*");
			bValid = oRexEx.IsMatch(email);
			
			return bValid;
		}
		
		static public string GetValidDbFieldName(string name)
		{
			string validName = string.Empty;
			name = HttpUtility.HtmlDecode(name);
			name = name.Replace("<br>", "");
			name = name.Replace("<br/>", "");
			name = name.Replace("<br />", "");
			Regex oRegEx = new Regex("\\w[\\w\\s]{0,126}");
			MatchCollection matches = oRegEx.Matches(name);
			
			foreach (Match item in matches)
			{
				validName += item.Value;
			}
			
			return validName;
		}
		
		//Given a string of charaters returns a string which is a valid control ID string
		static public string GetValidControlID(string name)
		{
			Regex oRexEx = default(Regex);
			
			string strControlID = "";
			
			name = name.Replace("\'", " ");
			
			char[] aryChars = name.ToCharArray();
			
			for (int iIndex = 0; iIndex <= aryChars.Length - 1; iIndex++)
			{
				if (IsValidXmlElementChar(Strings.AscW(aryChars[iIndex])))
				{
					strControlID += aryChars[iIndex].ToString();
				}
			}
			
			strControlID = strControlID.Replace(" ", "_");
			
			oRexEx = new Regex("^\\d");
			if (oRexEx.IsMatch(strControlID))
			{
				strControlID = "_" + strControlID;
			}
			
			return strControlID;
			
		}
		
		//Given a string of charaters returns a string which is an XML Safe string
		static public string GetValidXmlSafeString(string name)
		{
			Regex oRexEx = default(Regex);
			
			string strSafeXml = "";
			
			name = name.Replace("\\\'", " ");
			
			char[] aryChars = name.ToCharArray();
			
			for (int iIndex = 0; iIndex <= aryChars.Length - 1; iIndex++)
			{
				
				if (IsValidXmlElementChar(Strings.AscW(aryChars[iIndex])))
				{
					
					strSafeXml += aryChars[iIndex].ToString();
					
				}
			}
			
			strSafeXml = strSafeXml.Replace(" ", "_");
			
			oRexEx = new Regex("^\\d");
			
			if (oRexEx.IsMatch(strSafeXml))
			{
				
				strSafeXml = "_" + strSafeXml;
				
			}
			
			return strSafeXml;
			
		}
		
		//Verifies the a Character can be used as an Xml Element Name
		static public bool IsValidXmlElementChar(int charVal)
		{
			bool bIsValidChar = true;
			
			if (charVal < 31)
			{
				return false;
			}
			
			if (Between(charVal, 33, 47))
			{
				return false;
			}
			
			if (Between(charVal, 58, 64))
			{
				return false;
			}
			
			if (Between(charVal, 91, 94))
			{
				return false;
			}
			
			if (charVal == 96)
			{
				return false;
			}
			
			if (charVal == 215)
			{
				return false;
			}
			
			if (Between(charVal, 123, 191))
			{
				return false;
			}
			
			if (charVal == 2154)
			{
				return false;
			}
			
			if (charVal == 247)
			{
				return false;
			}
			
			if (Between(charVal, 8204, 64258))
			{
				return false;
			}
			
			return true;
			
		}
		
		//Helper for IsValidXmlElementChar
		static public bool Between(int intVal, int loVal, int highVal)
		{
			bool bIsBetween = false;
			
			if (intVal >= loVal && intVal <= highVal)
			{
				bIsBetween = true;
			}
			return bIsBetween;
		}
		
		//Verifies that a given Url is a valid format
		static public bool IsValidWebAddress(string address)
		{
			Regex oRexEx = default(Regex);
			
			oRexEx = new Regex("([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?");
			
			return oRexEx.IsMatch(address);
			
		}
		
		//Verifies that a given Url is a valid format
		static public bool IsValidDomainName(string domain)
		{
			Regex oRexEx = default(Regex);
			
			oRexEx = new Regex("^([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?$");
			
			return oRexEx.IsMatch(domain);
			
		}
		
		static public string GetPortalAlias(int portalId)
		{
			string strRetAlias = "";
			HttpContext oContext = HttpContext.Current;
			
			string scheme = oContext.Request.Url.Scheme;
			string host = oContext.Request.Url.Host;
			string port = (oContext.Request.Url.Port).ToString();
			string appPath = oContext.Request.ApplicationPath;
			
			if (appPath != "/")
			{
				appPath += "/";
			}
			
			strRetAlias = scheme + "://";
			
			strRetAlias += host;
			
			if (port != "80" && port != "443")
			{
				strRetAlias += ":" + port;
			}
			
			strRetAlias += appPath;
			
			return strRetAlias;
			
		}
		
		//Adds an Attribute to a given Element in a given XmlDocument
		static public XAttribute AddAttribute(XDocument xDoc, XElement xElemt, string AttributeName, string AttributeValue)
		{
			XAttribute oAttribute = null;
			
			if (xElemt != null)
			{
				oAttribute = (XAttribute) (xElemt.Attributes(AttributeName));
				if (oAttribute != null)
				{
					oAttribute.Value = AttributeValue;
				}
				else
				{
					xElemt.SetAttributeValue(AttributeName, AttributeValue);
					oAttribute = (XAttribute) (xElemt.Attributes(AttributeName));
				}
			}
			return oAttribute;
		}
		
		//Adds an Element to a Given XDocument, using the given parent element
		static public XElement AddElement(XDocument xDoc, XElement parentNode, string ElementName, string ElementValue, bool AsCDATA = false)
		{
			XElement xElementNode = null;
			
			if (parentNode != null)
			{
				if (AsCDATA)
				{
					parentNode.Add(new XElement(ElementName, new XCData(ElementValue)));
				}
				else
				{
					parentNode.Add(new XElement(ElementName, ElementValue));
				}
				xElementNode = parentNode.Element(ElementName);
			}
			return xElementNode;
		}
		
		//Gets the Module Settings for the Instance of the module
		//If not found in the Cache, creates a FormSettings Object and places it in the cache
		static public FormSettings GetFormSettings(int moduleID, double cacheTime = 60.0)
		{
			FormSettings objFormSettings = default(FormSettings);
			ModuleController objModCtrl = new ModuleController();
			Hashtable Settings = objModCtrl.GetModuleSettings(moduleID);
			HttpContext oContext = HttpContext.Current;
			string strCacheKey = "C5SLLC_FormSettings_" + moduleID.ToString();
			int intValue;

			if (oContext.Cache[strCacheKey] == null)
			{
				objFormSettings = new FormSettings();
				
				PropertyInfo[] properties = objFormSettings.GetType().GetProperties();
				foreach (PropertyInfo item in properties)
				{
					try
					{
						if (Settings.Contains(item.Name))
						{
							switch (item.PropertyType.Name)
							{
								case "Boolean":
									item.SetValue(objFormSettings, System.Convert.ToBoolean(Settings[item.Name]), null);
									break;
								case "String":
									item.SetValue(objFormSettings, System.Convert.ToString(Settings[item.Name]), null);
									break;
								case "Int32":
									item.SetValue(objFormSettings, System.Convert.ToInt32(Settings[item.Name]), null);
									break;
								case "DateTime":
									try
									{
										item.SetValue(objFormSettings, System.Convert.ToDateTime(Settings[item.Name]), null);
									}
									catch (Exception)
									{
										item.SetValue(objFormSettings, DateTime.Now, null);
									}
									break;
								case "EmailEncoding":
									if (int.TryParse(Settings[item.Name].ToString(), out intValue))
									{
										item.SetValue(objFormSettings, int.Parse(Settings[item.Name].ToString()).ToEnum<EmailEncoding>(), null);
									}
									else
									{
										item.SetValue(objFormSettings, Settings[item.Name].ToString().ToEnum<EmailEncoding>(), null);
									}
									break;
								case "TemplateType":
									if (int.TryParse(Settings[item.Name].ToString(), out intValue))
									{
										item.SetValue(objFormSettings, int.Parse(Settings[item.Name].ToString()).ToEnum<TemplateType>(), null);
									}
									else
									{
										item.SetValue(objFormSettings, Settings[item.Name].ToString().ToEnum<TemplateType>(), null);
									}
									break;
								case "HorizontalAlign":
									if (int.TryParse(Settings[item.Name].ToString(), out intValue))
									{
										item.SetValue(objFormSettings, int.Parse(Settings[item.Name].ToString()).ToEnum<HorizontalAlign>(), null);
									}
									else
									{
										item.SetValue(objFormSettings, Settings[item.Name].ToString().ToEnum<HorizontalAlign>(), null);
									}

									break;
								case "ValidationSummaryDisplayMode":
									if (int.TryParse(Settings[item.Name].ToString(), out intValue))
									{
										item.SetValue(objFormSettings, int.Parse(Settings[item.Name].ToString()).ToEnum<ValidationSummaryDisplayMode>(), null);
									}
									else
									{
										item.SetValue(objFormSettings, Settings[item.Name].ToString().ToEnum<ValidationSummaryDisplayMode>(), null);
									}
									break;
								case "ButtonType":
									if (int.TryParse(Settings[item.Name].ToString(), out intValue))
									{
										item.SetValue(objFormSettings, int.Parse(Settings[item.Name].ToString()).ToEnum<Code5Systems.FormMaster.Business.ButtonType>(), null);
									}
									else
									{
										item
											.SetValue(objFormSettings, Settings[item.Name].ToString().ToEnum<Code5Systems.FormMaster.Business.ButtonType>(), null);
									}
									break;
								case "CaptchaType":
									if (int.TryParse(Settings[item.Name].ToString(), out intValue))
									{
										item.SetValue(objFormSettings, int.Parse(Settings[item.Name].ToString()).ToEnum<CaptchaType>(), null);
									}
									else
									{
										item.SetValue(objFormSettings, Settings[item.Name].ToString().ToEnum<CaptchaType>(), null);
									}
									break;
							}
						}
					}
					catch (Exception ex)
					{
						DotNetNuke.Services.Exceptions.Exceptions.LogException(ex);
					}
				}
				
				int portalId = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings().PortalId;
				string homeDir = DotNetNuke.Entities.Portals.PortalController.GetCurrentPortalSettings().HomeDirectory;
				string portalGlobalsPath = HttpContext.Current.Server.MapPath(string.Format("{0}FormMaster/Globals.xml", homeDir));
				FileInfo fInfo = new FileInfo(portalGlobalsPath);
				if (!Directory.Exists(fInfo.DirectoryName))
				{
					Directory.CreateDirectory(fInfo.DirectoryName);
				}
				if (File.Exists(portalGlobalsPath))
				{
					XDocument xDoc = XDocument.Load(portalGlobalsPath);
					
					XElement xUseTransactions = (from u in xDoc.Root.Elements("UseTransactions") select u).FirstOrDefault();
					if (xUseTransactions != null)
					{
						if (!string.IsNullOrEmpty(xUseTransactions.Value))
						{
							objFormSettings.UseTransactions = bool.Parse(xUseTransactions.Value);
						}
					}
					
					System.Xml.Linq.XElement xPortal = (from p in xDoc.Root.Elements("Portal") 
														where System.Convert.ToInt32(p.Attributes("PortalID").First().Value) == portalId 
														select p).FirstOrDefault();
					if (xPortal != null)
					{
						XElement xUploadPath = (from u in xPortal.Elements("UploadPath") select u).FirstOrDefault();
						if (xUploadPath != null)
						{
							if (!string.IsNullOrEmpty(xUploadPath.Value))
							{
								objFormSettings.GlobalUploadPath = xUploadPath.Value;
							}
						}
						
						XElement xDoLogging = (from u in xPortal.Elements("DoLogging") 
											   select u).FirstOrDefault();
						if (xDoLogging != null)
						{
							if (!string.IsNullOrEmpty(xDoLogging.Value))
							{
								objFormSettings.DoLogging = bool.Parse(xDoLogging.Value);
							}
						}
					}
				}
				else
				{
					string globalsPath = HttpContext.Current.Server.MapPath("~/DesktopModules/Code5Systems_FormMaster/assets/xml/Globals.xml");
					fInfo = new FileInfo(globalsPath);
					fInfo.CopyTo(portalGlobalsPath);
				}
				
				System.Web.Caching.CacheDependency dependancy = new System.Web.Caching.CacheDependency(portalGlobalsPath);
				
				oContext.Cache.Insert(strCacheKey, objFormSettings, dependancy, DateTime.MaxValue, TimeSpan.FromMinutes(cacheTime), System.Web.Caching.CacheItemPriority.Normal, null);
			}
			else
			{
				objFormSettings = (FormSettings) (oContext.Cache[strCacheKey]);
			}
			
			return objFormSettings;
			
		}
		
		static public void SaveFormSettings(int ModuleID, FormSettings oFormSettings, List<string> settingsToSave = null)
		{
			ModuleController objModules = new ModuleController();
			PropertyInfo[] properties = oFormSettings.GetType().GetProperties();
			PropertyInfo oProperty = default(PropertyInfo);
			string settingName = default(string);
			
			if (settingsToSave != null)
			{
				foreach (string setting in settingsToSave)
				{
					settingName = setting;
					oProperty = properties.Where(p => p.Name == settingName).FirstOrDefault();
					if (oProperty != null)
					{
						try
						{
							objModules.UpdateModuleSetting(ModuleID, settingName, System.Convert.ToString(oProperty.GetValue(oFormSettings, null)));
						}
						catch
						{
							// Ignore errors Settings will take the default value.
						}
						
					}
				}
			}
			else
			{
				foreach (PropertyInfo item in properties)
				{
					try
					{
						objModules.UpdateModuleSetting(ModuleID, item.Name, System.Convert.ToString(item.GetValue(oFormSettings, null)));
					}
					catch
					{
						// Ignore errors Settings will take the default value.
					}
				}
			}
		}
		
		static public void SetCookie(string cookieName, string cookieValue, DateTime expireDate)
		{
			HttpContext oContext = default(HttpContext);
			oContext = HttpContext.Current;
			
			HttpCookie cookie = default(HttpCookie);
			cookie = new HttpCookie(cookieName, cookieValue);
			
			if (expireDate > DateTime.MinValue)
			{
				cookie.Expires = expireDate;
			}
			
			oContext.Response.Cookies.Add(cookie);
		}
		
		static public void DeleteCookie(string cookieName)
		{
			HttpContext oContext = default(HttpContext);
			HttpCookie cookie = default(HttpCookie);
			
			oContext = HttpContext.Current;
			oContext.Request.Cookies.Remove(cookieName);
			
			cookie = oContext.Request.Cookies[cookieName];
			if (cookie != null)
			{
				oContext.Request.Cookies.Remove(cookieName);
				cookie.Expires = DateTime.Now.AddYears(-30);
				oContext.Response.Cookies.Add(cookie);
			}
			
		}
		
		static public string GetCookieValue(string cookieName)
		{
			HttpContext oContext = default(HttpContext);
			HttpCookie cookie = default(HttpCookie);
			string strValue = "";
			
			oContext = HttpContext.Current;
			cookie = oContext.Request.Cookies[cookieName];
			if (cookie != null)
			{
				strValue = cookie.Value;
			}
			
			return strValue;
			
		}
		
		static public void AddSessionItem(string name, object value)
		{
			HttpContext.Current.Session.Add(name, value);
		}
		
		static public bool SessionItemExists(string name)
		{
			return HttpContext.Current.Session[name] != null;
		}
		
		static public T GetSessionItem<T>(string name)
		{
			T value = default(T);
			if (HttpContext.Current.Session[name] != null)
			{
				value = (T) (HttpContext.Current.Session[name]);
			}
			return value;
		}
		
		static public void ClearSessionItem(string name)
		{
			HttpContext.Current.Session.Remove(name);
		}
		
		static public string GetAppPath()
		{
			HttpContext oContext = default(HttpContext);
			oContext = HttpContext.Current;
			
			string strPath = oContext.Request.ApplicationPath;
			
			if (strPath != "/")
			{
				strPath += "/";
			}
			
			return strPath;
			
		}
		
		static public string GetRuntimePath()
		{
			string strPath = GetAppPath();
			strPath += "DesktopModules/Code5Systems_FormMaster";
			return strPath;
		}
		
		static public string GetSharedResourceFile()
		{
			
			string strPath = GetAppPath();
			
			strPath += "DesktopModules/Code5Systems_FormMaster/App_LocalResources/SharedResources";
			
			if (Thread.CurrentThread.CurrentCulture.Name != "en-US")
			{
				strPath += "." + Thread.CurrentThread.CurrentCulture.Name;
			}
			
			strPath += ".resx";
			
			return strPath;
			
		}
		
		static public string EncryptString(string toEncyrpt)
		{
			string encrypted = "";
			if (!String.IsNullOrWhiteSpace(toEncyrpt))
			{
				if (toEncyrpt != string.Empty)
				{
					byte[] buffer = ASCIIEncoding.ASCII.GetBytes(toEncyrpt);

					RijndaelManaged rijndael = new RijndaelManaged();

					rijndael.Key = Convert.FromBase64String(GetKey());

					rijndael.IV = Convert.FromBase64String(GetIV());

					encrypted = Convert.ToBase64String(rijndael.CreateEncryptor().TransformFinalBlock(buffer, 0, buffer.Length));
				}
			}
			
			return encrypted;
			
		}
		
		static public string DecryptString(string toDeCrypt)
		{
			string decrypted = "";
			byte[] buffer = null;
			
			if (toDeCrypt != string.Empty)
			{
				try
				{
					buffer = Convert.FromBase64String(toDeCrypt);
				}
				catch (Exception)
				{
					return toDeCrypt;
				}
				
				RijndaelManaged rijndael = new RijndaelManaged();
				
				rijndael.Key = Convert.FromBase64String(GetKey());
				
				rijndael.IV = Convert.FromBase64String(GetIV());
				
				decrypted = (string) (ASCIIEncoding.ASCII.GetString(rijndael.CreateDecryptor().TransformFinalBlock(buffer, 0, buffer.Length)));
			}
			
			return decrypted;
			
		}
		
		static public string GetCsvFromNodeList(IEnumerable<XElement> nodes)
		{
			string strCsv = string.Empty;
			
			foreach (XElement oNode in nodes)
			{
				if (!string.IsNullOrEmpty(oNode.Value))
				{
					if (oNode.Name != "ARToken")
					{
						strCsv += oNode.Value + ",";
					}
				}
			}
			
			if (strCsv.Length > 0)
			{
				strCsv = strCsv.Substring(0, strCsv.Length - 1);
			}
			
			return strCsv;
			
		}
		
		public static void LocalizeGridView(GridView gv, string ResourceFile)
		{
			string key = default(string);
			string localizedText = default(string);
			System.Reflection.PropertyInfo pi = default(System.Reflection.PropertyInfo);
			
			foreach (DataControlField col in gv.Columns)
			{
				key = col.HeaderText;
				if (key != "")
				{
					localizedText = Localization.GetString(key + ".Header", ResourceFile);
					if (localizedText != "")
					{
						col.HeaderText = localizedText;
					}
				}
				
				//Localize text of Cancel, Delete, Edit, Insert, Select, New, Update buttons
				if (col is CommandField)
				{
					CommandField cmdField = (CommandField) col;
					foreach (string cmdName in new string[] {"Cancel", "Delete", "Edit", "Insert", "Select", "New", "Update"})
					{
						pi = cmdField.GetType().GetProperty(cmdName + "Text", typeof(string));
						key = System.Convert.ToString(pi.GetValue(cmdField, null));
						if (!string.IsNullOrEmpty(key))
						{
							localizedText = Localization.GetString(key + ".CommandText", ResourceFile);
							if (localizedText != "")
							{
								pi.SetValue(cmdField, localizedText, null);
							}
						}
					}
				}
			}
		}
		
		public static void DisableAjax(Control control)
		{
			
			string controlType = string.Empty;
			ScriptManager oScriptMgr = default(ScriptManager);
			oScriptMgr = (ScriptManager) (control.Page.FindControl("scriptmanager"));
			
			if (!control.NamingContainer.ToString().Contains("formmaster"))
			{
				return;
			}
			
			if (oScriptMgr == null)
			{
				return;
			}
			
			controlType = (string) (control.GetType().ToString().ToLower());
			if (controlType.Contains("button"))
			{
				controlType = "button";
			}
			else if (controlType.Contains("list"))
			{
				if (!controlType.Contains("validator"))
				{
					controlType = "list";
				}
			}
			else if (controlType.Contains("checkbox"))
			{
				controlType = "checkbox";
			}
			
			switch (controlType)
			{
				case "button":
					oScriptMgr.RegisterPostBackControl(control);
					break;
				case "list":
					ListControl oListCtl = (ListControl) control;
					if (oListCtl.AutoPostBack)
					{
						oScriptMgr.RegisterPostBackControl(control);
					}
					break;
				case "checkbox":
					CheckBox oChkBox = (CheckBox) control;
					if (oChkBox.AutoPostBack)
					{
						oScriptMgr.RegisterPostBackControl(control);
					}
					break;
				default:
					if (control.HasControls())
					{
						foreach (Control ctl in control.Controls)
						{
							DisableAjax(ctl);
						}
					}
					break;
			}
		}
		
		public static Code5Systems.FormMaster.Business.DocType GetPageDocType(Control container)
		{
			Code5Systems.FormMaster.Business.DocType pageDocType = Code5Systems.FormMaster.Business.DocType.HTML40;
			
			Control objDoctype = container.Page.FindControl("skinDocType");
			
			if (objDoctype != null)
			{
				string strDocType = ((Literal) objDoctype).Text;
				if (strDocType.Contains("XHTML 1.0"))
				{
					pageDocType = Code5Systems.FormMaster.Business.DocType.XHTML10;
				}
				else if (strDocType.Contains("XHTML 1.1"))
				{
					pageDocType = Code5Systems.FormMaster.Business.DocType.XHTML11;
				}
			}
			
			return pageDocType;
			
		}
		
		public static CultureInfo GetUserCulture()
		{
			PortalSettings _portalSettings = null;
			CultureInfo userCulture = null;
			
			_portalSettings = DotNetNuke.Common.Globals.GetPortalSettings();
			
			// Obtain PortalSettings from Current Context
			UserInfo objUserInfo = UserController.GetCurrentUserInfo();
			
			DotNetNuke.Services.Localization.LocaleCollection enabledLocales = DotNetNuke.Services.Localization.Localization.GetEnabledLocales();
			
			//used as temporary variable to get info about the preferred locale
			string preferredLocale = string.Empty;
			//used as temporary variable where the language part of the preferred locale will be saved
			string preferredLanguage = string.Empty;
			
			//first try if a specific language is requested by cookie, querystring, or form
			if (!(HttpContext.Current == null))
			{
				try
				{
					preferredLocale = HttpContext.Current.Request["language"];
					if (preferredLocale != "")
					{
						if (DotNetNuke.Services.Localization.Localization.LocaleIsEnabled(preferredLocale))
						{
							userCulture = new CultureInfo(preferredLocale);
						}
						else
						{
							preferredLanguage = (string) (preferredLocale.Split('-')[0]);
						}
					}
				}
				catch
				{
				}
			}
			
			if (userCulture == null)
			{
				// next try to get the preferred language of the logged on user
				if (objUserInfo.UserID != -1)
				{
					if (objUserInfo.Profile.PreferredLocale != "")
					{
						if (DotNetNuke.Services.Localization.Localization.LocaleIsEnabled(preferredLocale))
						{
							userCulture = new CultureInfo(objUserInfo.Profile.PreferredLocale);
						}
						else
						{
							if (preferredLanguage == "")
							{
								preferredLanguage = (string) (objUserInfo.Profile.PreferredLocale.Split('-')[0]);
							}
						}
					}
				}
			}
			
			if (userCulture == null)
			{
				// use Request.UserLanguages to get the preferred language
				if (!(HttpContext.Current == null))
				{
					if (!(HttpContext.Current.Request.UserLanguages == null))
					{
						try
						{
							foreach (string userLang in HttpContext.Current.Request.UserLanguages)
							{
								//split userlanguage by ";"... all but the first language will contain a preferrence index eg. ;q=.5
								string userlanguage = (string) (userLang.Split(';')[0]);
								if (DotNetNuke.Services.Localization.Localization.LocaleIsEnabled(userlanguage))
								{
									userCulture = new CultureInfo(userlanguage);
								}
								else if (userLang.Split(';')[0].IndexOf("-") != -1)
								{
									//if userLang is neutral we don't need to do this part since
									//it has already been done in LocaleIsEnabled( )
									string templang = (string) (userLang.Split(';')[0]);
									foreach (string _localeCode in enabledLocales.AllKeys)
									{
										if (_localeCode.Split('-')[0] == templang.Split('-')[0])
										{
											//the preferredLanguage was found in the enabled locales collection, so we are going to use this one
											//eg, requested locale is en-GB, requested language is en, enabled locale is en-US, so en is a match for en-US
											userCulture = new CultureInfo(_localeCode);
											break;
										}
									}
								}
								if (userCulture != null)
								{
									break;
								}
							}
						}
						catch
						{
						}
					}
				}
			}
			
			if (userCulture == null && preferredLanguage != "")
			{
				//we still don't have a good culture, so we are going to try to get a culture with the preferredlanguage instead
				foreach (string _localeCode in enabledLocales.AllKeys)
				{
					if (_localeCode.Split('-')[0] == preferredLanguage)
					{
						//the preferredLanguage was found in the enabled locales collection, so we are going to use this one
						//eg, requested locale is en-GB, requested language is en, enabled locale is en-US, so en is a match for en-US
						userCulture = new CultureInfo(_localeCode);
						break;
					}
				}
			}
			
			//we still have no culture info set, so we are going to use the fallback method
			if (userCulture == null)
			{
				if (_portalSettings.DefaultLanguage == "")
				{
					// this is a last resort, as the portal default language should always be set
					// however if its not set, return the first enabled locale
					// if there are no enabled locales, return the systemlocale
					if (enabledLocales.Count > 0)
					{
						userCulture = new CultureInfo(System.Convert.ToString(enabledLocales[0].Key));
					}
					else
					{
						userCulture = new CultureInfo((string) DotNetNuke.Services.Localization.Localization.SystemLocale);
					}
				}
				else
				{
					// as the portal default language can never be disabled, we know this language is available and enabled
					userCulture = new CultureInfo(_portalSettings.DefaultLanguage);
				}
			}
			
			if (userCulture == null)
			{
				//just a safeguard, to make sure we return something
				userCulture = new CultureInfo((string) DotNetNuke.Services.Localization.Localization.SystemLocale);
			}
			
			return userCulture;
		}
																											
		public static string GetRegistrationResponse(UserCreateStatus status)
		{
			string retVal = string.Empty;
																																			
			switch (status)
			{
				case UserCreateStatus.DuplicateEmail:
					retVal = Localization.GetString("UCSDuplicateEmail", GetSharedResourceFile());
					break;
																																					
				case UserCreateStatus.DuplicateProviderUserKey:
					retVal = Localization.GetString("UCSDuplicateProviderUserKey", GetSharedResourceFile());
					break;
																																					
				case UserCreateStatus.DuplicateUserName:
					retVal = Localization.GetString("UCSDuplicateUserName", GetSharedResourceFile());
					break;
																																					
				case UserCreateStatus.InvalidEmail:
					retVal = Localization.GetString("UCSInvalidEmail", GetSharedResourceFile());
					break;
																																					
				case UserCreateStatus.InvalidAnswer:
					retVal = Localization.GetString("UCSInvalidAnswer", GetSharedResourceFile());
					break;
																																					
				case UserCreateStatus.InvalidPassword:
					retVal = Localization.GetString("UCSInvalidPassword", GetSharedResourceFile());
					break;
																																					
				case UserCreateStatus.InvalidProviderUserKey:
					retVal = Localization.GetString("UCSInvalidProviderUserKey", GetSharedResourceFile());
					break;
																																					
				case UserCreateStatus.InvalidUserName:
					retVal = Localization.GetString("UCSInvalidUserName", GetSharedResourceFile());
					break;
																																					
				case UserCreateStatus.ProviderError:
					retVal = Localization.GetString("UCSProviderError", GetSharedResourceFile());
					break;
																																					
				case UserCreateStatus.PasswordMismatch:
					retVal = Localization.GetString("UCSPasswordMismatch", GetSharedResourceFile());
					break;
																																					
				case UserCreateStatus.InvalidQuestion:
					retVal = Localization.GetString("UCSInvalidQuestion", GetSharedResourceFile());
					break;
																																					
				case UserCreateStatus.UserAlreadyRegistered:
					retVal = Localization.GetString("UCSUserAlreadyRegistered", GetSharedResourceFile());
					break;
																																					
				case UserCreateStatus.UsernameAlreadyExists:
					retVal = Localization.GetString("UCSUsernameAlreadyExists", GetSharedResourceFile());
					break;
																																					
				case UserCreateStatus.UserRejected:
					retVal = Localization.GetString("UCSUserRejected", GetSharedResourceFile());
					break;
																																					
				default:
					retVal = Localization.GetString("UCSUnexpectedError", GetSharedResourceFile());
					break;
			}
																																			
			return retVal;
																																			
		}
																																		
		[System.Reflection.Obfuscation(Feature = "cw symbol renaming", Exclude = true)]
		public static string XmlSerialize<T>(T toSerialize)
		{
			string serialized = default(string);
																																			
			XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
			ns.Add("", "");
																																			
			XmlWriterSettings writerSettings = new XmlWriterSettings();
			writerSettings.OmitXmlDeclaration = true;
																																			
			StringWriter sw = new StringWriter();
																																			
			System.Xml.Serialization.XmlSerializer itemSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
																																			
			using (XmlWriter xmlWriter = XmlWriter.Create(sw, writerSettings))
			{
				itemSerializer.Serialize(xmlWriter, toSerialize, ns);
			}
																																			
																																			
			serialized = sw.ToString();
																																			
			return serialized;
		}
																																		
		[System.Reflection.Obfuscation(Feature = "cw symbol renaming", Exclude = true)]
		public static T XmlDeserialize<T>(string toDeserialize)
		{
			T deserialized = default(T);
			System.Xml.Serialization.XmlSerializer itemSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T));
																																			
			using (StringReader reader = new StringReader(toDeserialize))
			{
				deserialized = (T) (itemSerializer.Deserialize(System.Xml.XmlReader.Create(reader)));
			}
																																																																	
			return deserialized;
		}
																																		
		[System.Reflection.Obfuscation(Feature = "cw symbol renaming", Exclude = true)]
		public static string JsonSerialize<T>(T toSerialize)
		{
			string serialized = default(string);
			DataContractJsonSerializer itemSerializer = default(DataContractJsonSerializer);
																																			
			if (typeof(T).IsInterface)
			{
				itemSerializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(toSerialize.GetType());
			}
			else
			{
				itemSerializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
			}
																																			
			using (MemoryStream mem = new MemoryStream())
			{
				itemSerializer.WriteObject(mem, toSerialize);
				serialized = Encoding.UTF8.GetString(mem.ToArray(), 0, (int) mem.Length);
			}
																																			
																																			
			return serialized;
																																			
		}
																																		
		[System.Reflection.Obfuscation(Feature = "cw symbol renaming", Exclude = true)]
		public static T JsonDeserialize<T>(string toDeserialize)
		{
			T deserialized = default(T);
																																			
			DataContractJsonSerializer itemSerializer = new DataContractJsonSerializer(typeof(T));
			using (MemoryStream mem = new MemoryStream(Encoding.UTF8.GetBytes(toDeserialize)))
			{
				deserialized = (T) (itemSerializer.ReadObject(mem));
			}
																																			
																																			
			return deserialized;
		}
																																		
		public static System.Collections.Generic.IEnumerable<Control> GetChildsRecursive(Control root)
		{
			List<Control> ctls = new List<Control>();
			ctls.Add(root);
			int childCount = root.Controls.Count;
			for (int i = 0; i <= childCount - 1; i++)
			{
				ctls.AddRange(GetChildsRecursive(root.Controls[i]));
			}
			return ctls;
		}

		public static void RemoveControlRecursive(Control ctl)
		{
			var parent = ctl.Parent;
			parent.Controls.Remove(ctl);
			if (parent.Controls.Count == 0)
			{
				RemoveControlRecursive(parent);
			}
		}
																																		
		public static string GetAppVersion()
		{
			string fileVersion = "0.0.0.0";
																																			
			try
			{
				Assembly theAssembly = Assembly.GetCallingAssembly();
				if (theAssembly == null)
				{
					theAssembly = Assembly.GetExecutingAssembly();
				}
																																				
				object[] names = theAssembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
																																				
				object[] attributes = theAssembly.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false);
				if (attributes.Length != 0)
				{
					fileVersion = (string) ((((AssemblyFileVersionAttribute) (attributes[0])) ).Version.ToString());
				}
			}
			catch
			{
																																				
			}
																																			
			return fileVersion;
		}
																																		
		public static string GetAppTitle()
		{
			string title = "Form Master";
																																			
			try
			{
				Assembly theAssembly = Assembly.GetCallingAssembly();
				if (theAssembly == null)
				{
					theAssembly = Assembly.GetExecutingAssembly();
				}
																																				
				object[] attributes = theAssembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
				if (attributes.Length != 0)
				{
					title = (string) ((((AssemblyTitleAttribute) (attributes[0])) ).Title.ToString());
				}
			}
			catch
			{
																																				
			}
																																			
			return title;
		}

		public static System.Version GetDNNVersion()
		{
			return DotNetNuke.Application.DotNetNukeContext.Current.Application.Version;
		}
																																		
		public static void DoLogging(int portalId, int moduleId, string message, ModuleInstanceContext context = null)
		{
			StringBuilder sb = new StringBuilder();
			string filePath = string.Empty;
			string folderPath = default(string);
																																			
			try
			{
				FormSettings objSettings = GetFormSettings(moduleId);
																																				
				if (portalId < 0)
				{
					return ;
				}
																																				
				if (moduleId < 1)
				{
					return ;
				}
																																				
				if (!objSettings.DoLogging)
				{
					return ;
				}
																																				
				folderPath = Utility.GetAppPath();
				folderPath += "Portals/" + portalId.ToString() + "/FormMaster";
				if (!Directory.Exists(HttpContext.Current.Server.MapPath(folderPath)))
				{
					Directory.CreateDirectory(HttpContext.Current.Server.MapPath(folderPath));
				}
				filePath = folderPath + "/FormMaster.log";
				filePath = HttpContext.Current.Server.MapPath(filePath);
				sb.Append(Environment.NewLine);
				if (context != null)
				{
					sb.Append(string.Format("{0:yyyy-MM-dd H:mm:ss zzz} PortalID: {1} ModuleID: {2} Title: {3}{4}", DateTime.UtcNow, portalId, moduleId, context.Configuration.ModuleTitle, Environment.NewLine));
				}
				else
				{
					ModuleController modCtlr = new DotNetNuke.Entities.Modules.ModuleController();
					ModuleInfo modInfo = modCtlr.GetModule(moduleId);
					sb.Append(string.Format("{0:yyyy-MM-dd H:mm:ss zzz} PortalID: {1} ModuleID: {2} Title: {3}{4}", DateTime.UtcNow, portalId, moduleId, modInfo.ModuleTitle, Environment.NewLine));
				}
																																				
				sb.Append(message);
																																				
				File.AppendAllText(filePath, sb.ToString());
																																				
			}
			catch (Exception)
			{
																																				
			}
		}

		public static string JsonMessageResult(string message, bool success, JsonDataType dataType = JsonDataType.Json)
		{
			JsonResult result = new JsonResult();
			result.DataType = dataType.ToString();
			result.Result = message;
			result.Success = success;
			return JsonSerialize<JsonResult>(result);
		}
																																		
		private static string GetKey()
		{
			return "SW7pej0kqGWgDGbZpAAr8+LkW+/FQTYvYbkIryVPb5o=";
		}
																																		
		private static string GetIV()
		{
			return "iGC2ySr0keyRttX6eyHtJw==";
		}
																																		
		internal static string GetApiKey()
		{
			return "As51HNyOVGrk5WfUkYY8K5njnlTrZabdLM47QjHYM+6juUYe7SzWdvLM5F+Hv//HnY5GMXujDTPUGJClLXh5PgXXM3ziVOPC2z/Wgd/u+ISiz3E3bW/cQjo2DYSC+QJXaEE15QkWofRSDvlfQdJ59ixTf54AExgYxWad7ucXdsarvo58bGpWoSEBdx2VJeku9Vfgo/WU44vz+pjegIC8kFNfe93WOjxwspTSl9x+UJPth/Jm7RPO4iUoAEBwEmovW2W0nBU/o9tW4FIgkGiOOq/CLm2jaoGcU0Ap2xzkFy8=";
		}

		internal static string GetReCaptchaDomain()
		{
			return "global-key.code5systems.com";
		}

		internal static string GetReCaptchaPublicKey()
		{
			return "6LfpfukSAAAAAG69XH_RvmdTH1MFt7yYInHBUoGQ";
		}

		internal static string GetReCaptchaPrivateKey()
		{
			return "6LfpfukSAAAAAAQkfdHajkqwmVvr6JEwGg2_SlXY";
		}
																																		
		internal static Dictionary<string, List<string>> GetPageScriptsDictionary()
		{
			Dictionary<string, List<string>> pageScripts = new Dictionary<string, List<string>>();
			pageScripts.Add(Code5Systems.FormMaster.Business.Constants.DECLARATIONS, new List<string>());
			pageScripts.Add(Code5Systems.FormMaster.Business.Constants.FUNCTIONS, new List<string>());
			pageScripts.Add(Code5Systems.FormMaster.Business.Constants.DOCREADY, new List<string>());
			pageScripts.Add(Code5Systems.FormMaster.Business.Constants.PAGELOAD, new List<string>());
			pageScripts.Add(Code5Systems.FormMaster.Business.Constants.PAGELOADEND, new List<string>());
			return pageScripts;
		}
																																		
		internal static string FixLegacyLabels(string formDefinition)
		{
		XDocument xDoc = XDocument.Parse(formDefinition);
		IEnumerable<XElement> xControls = default(IEnumerable<XElement>);
		XAttribute xLabelAttr = default(XAttribute);
		System.Collections.Generic.IEnumerable<XElement> xLabels = xDoc.Descendants("Label");
																																			
		if (xLabels.Count() == 0)
		{
			xControls = xDoc.Descendants("Control");
			foreach (XElement item in xControls)
			{
				xLabelAttr = item.Attribute("Label");
				if (xLabelAttr != null)
				{
					item.Add(new XElement("Label", new XCData(xLabelAttr.Value)));
					item.Add(new XAttribute("FieldName", Utility.GetValidDbFieldName(xLabelAttr.Value)));
					xLabelAttr.Remove();
				}
			}
		}
																																			
		return xDoc.ToString();
		}
																																		
		internal static string GetApiEndpoint()
		{
#if DEBUG
			return "http://localhost:54083/Lic";
			//return "https://licensing.code5systems.com/Lic";
#else
			return "https://licensing.code5systems.com/Lic";
#endif
		}																																																															
	}
																																	
#endregion
																																	
}
																																
